const generateLog = require('./Utils/logger');//日志模块
const path = require('path');//路径插件

const nodemailer = require('nodemailer');//邮件模块

const { readTextFile, writeTextFile } = require('./Utils/textFileReader');//读取邮件数据

// 日期模块
const dateUtils = require('./Utils/getDate'); // 假设date-utils.js在同一目录下  
const { readFile } = require('fs');
const todayDate = dateUtils.getTodayDate(); // 获取今天的日期

//定义要发送的临时数据变量
var subject = "Hello from account"
var ADNB = 0;
var text = 'This is a test email from the first account.'
var emailData = {}

// 日志模块初始化
const logFilePath = path.join(__dirname, './Log/appRun.log'); // 日志文件路径
const message = 'This is  system log,下面是本次(' + todayDate + ')邮件发送日志：'; // 要记录的日志消息
generateLog(logFilePath, message);


// 直接读取多个发送方账户
var Sendaccounts = [];
var receiveAccounts = []
const parseTextFile = require('./Utils/parseTxtFile');
const SendAccountfilePath = './txt/SendAccounts.txt'; // 文件路径
// const delayT = require('./Utils/delay').default; // 假设delay.js位于同一目录下  


const readFileToArray = require('./Utils/readReceiveAccount');//收件人读取模块
const receivefilePath = './txt/receiveAccounts.txt'; // 收件人文件路径
const filePath = './txt/EmailMessage.txt'; //邮件正文文本文件路径
var SendTotal = 0;

//发送邮件
async function sendEmail(Sendaccounts, receiveAccounts, accountIndex, emailData) {
    try {
        // 创建不同账号的邮件发送器  
        const transporter = nodemailer.createTransport({
            service: 'qq',
            auth: {
                user: Sendaccounts[accountIndex].user,
                pass: Sendaccounts[accountIndex].pass,
            },
        });
        // 设置邮件内容  
        const R_Nmae = receiveAccounts[accountIndex].split('@'); //取出收件人名字
        var mailOptions = {
            from: Sendaccounts[accountIndex].user,
            to: receiveAccounts[accountIndex],
            subject: emailData.subject + accountIndex,
            text:emailData.first+"  "+ R_Nmae[0]+"\n\r" + '              '+emailData.text + "\n\n" + `${Sendaccounts[accountIndex].name}`,
        };
        // console.log("RS:", mailOptions);

        // 发送邮件  
        const info = await transporter.sendMail(mailOptions);
        generateLog(logFilePath, "成功:" + `Message sent: ${info.messageId}` + ',S:' + Sendaccounts[accountIndex].user + ',R:' + receiveAccounts[accountIndex]);
    } catch (error) {
        // console.error(`Error sending email: ${error}`);
        generateLog(logFilePath, "失败:" + `Error sending: ${error}` + ',S:' + Sendaccounts[accountIndex].user + ',R:' + receiveAccounts[accountIndex]);
    }
}

// 发送邮件
async function sendEmails(Sendaccounts, receiveAccounts, ADNB, emailData) {
    for (const Account of receiveAccounts) {
        await delay(3000);
        if (SendTotal >= receiveAccounts.length) {
            generateLog(logFilePath, "表格中的邮箱全部发送完毕！");
            console.log("表格中的邮箱全部发送完毕！");
        } else {
            await sendEmail(Sendaccounts, receiveAccounts, ADNB, emailData);
            SendTotal++;
        }
        if (ADNB >= Sendaccounts.length) {
            ADNB = 0;
        } else {
            ADNB++;
        }
    }
}

// 定义邮件发送延迟函数
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}


// --------------异步执行全部异步函数--------------------------------------------
async function runAsyncFunctions() {
    try {
        await parseTextFile(SendAccountfilePath).then(data => {  //读取发件人
            Sendaccounts = data;
            // console.log('解析后的对象数组：', Sendaccounts);
        })
            .catch(error => {
                console.error('读取发件人错误:', error);
            });

        await readFileToArray(receivefilePath) //读取收件人
            .then(receiveEmails => {
                receiveAccounts = receiveEmails;  //执行后程序不能跳出
            })
            .catch(error => {
                console.error('读取收件人出错:', error);
            });

        await readTextFile(filePath, 1, 1)  //读取主题
            .then(content => {
                subject = content;
                emailData.subject = subject;
                // console.log("主题:" + subject);
            }).catch(error => {
                console.error('读取主题出错:', error);
            });

        await readTextFile(filePath, 3, 3)  //读取正文首行
            .then(content => {
                first = content;
                emailData.first = first;
                // console.log("首行:" , emailData.first);
            }).catch(error => {
                console.error('读取主题出错:', error);
            });

        await readTextFile(filePath, 5, 14)  //读取正文
            .then(content => {
                text = content
                emailData.from = ADNB // 使用第0个账户发送  
                emailData.to = receiveAccounts[ADNB]
                emailData.text = text
                // console.log("emailData-text:", emailData.text);
            }).catch(error => {
                console.error('读取正文出错:', error);
            });
        // console.log("发送账户数组:", Sendaccounts)
        // console.log("接收账户数组:", receiveAccounts)
        await sendEmails(Sendaccounts, receiveAccounts, ADNB, emailData);
    } catch (error) {
        console.error('Error:', error);
    }
}

runAsyncFunctions();